package com.ruoyi.web.controller.gcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.SjProcessConfig;
import com.ruoyi.gcgl.domain.SjProjectPeople;
import com.ruoyi.gcgl.domain.YyProject;
import com.ruoyi.gcgl.domain.YyProjectDesignFun;
import com.ruoyi.gcgl.service.IGcCustomerService;
import com.ruoyi.gcgl.service.ISjProcessConfigService;
import com.ruoyi.gcgl.service.ISjProjectPeopleService;
import com.ruoyi.gcgl.service.IYyProjectDesignFunService;
import com.ruoyi.gcgl.service.IYyProjectService;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 项目设计工作联系函Controller
 * 
 * @author ruoyi
 * @date 2025-08-07
 */
@Controller
@RequestMapping("/yy/fun")
public class YyProjectDesignFunController extends BaseController
{
    private String prefix = "yy/fun";

    @Autowired
    private IYyProjectDesignFunService sjProjectDesignFunService;
    @Autowired
    private ISjProjectPeopleService sjProjectPeopleService;
    @Autowired
    private IYyProjectService gcProjectService;
    @Autowired
    private IGcCustomerService gcCustomerService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Autowired
    private ISjProcessConfigService sjProcessConfigService;
    @Autowired
    private ISysDeptService deptService;
    
    final String processCode = "sjhanjian";

    @GetMapping()
    public String fun()
    {
        return prefix + "/fun";
    }
    
    /**
     * 查询项目设计工作联系函列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YyProjectDesignFun sjProjectDesignFun)
    {
        startPage();
        sjProjectDesignFun.setDeleteFlag(1);
        sjProjectDesignFun.setType(1);
        List<YyProjectDesignFun> list = sjProjectDesignFunService.selectSjProjectDesignFunList(sjProjectDesignFun);
        
        return getDataTable(list);
    }

    /**
     * 导出项目设计工作联系函列表
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setDeleteFlag(1);
        List<YyProjectDesignFun> list = sjProjectDesignFunService.selectSjProjectDesignFunList(sjProjectDesignFun);
        ExcelUtil<YyProjectDesignFun> util = new ExcelUtil<YyProjectDesignFun>(YyProjectDesignFun.class);
        return util.exportExcel(list, "项目设计工作联系函数据");
    }

    /**
     * 新增项目设计工作联系函
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") Long id, ModelMap mmap){
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	mmap.put("owner", getLoginName());
    	mmap.put("ownerId", getUserId());
    	mmap.put("deptName", getSysUser().getDept().getDeptName());
    	mmap.put("deptId", getSysUser().getDept().getDeptId());
    	
    	//下一级审核人
        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
        mmap.put("approveid", configlis.get(0).getLevel1id());
        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/add";
    }

    /**
     * 新增保存项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setStatus(1);//状态1
    	sjProjectDesignFun.setDeleteFlag(1);
    	sjProjectDesignFun.setCreateUser(getLoginName());
    	sjProjectDesignFun.setCreateAt(new Date());
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.insertSjProjectDesignFun(sjProjectDesignFun));
    }

    /**
     * 修改项目设计工作联系函
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        YyProjectDesignFun sjProjectDesignFun = sjProjectDesignFunService.selectSjProjectDesignFunById(id);
        
        if(sjProjectDesignFun.getHfunfile()!=null && !sjProjectDesignFun.getHfunfile().equals("")){
        	String[] zlis = sjProjectDesignFun.getHfunfile().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zilwjvo", file);
        }else{
        	mmap.put("zilwjvo", "");
        }
        mmap.put("sjProjectDesignFun", sjProjectDesignFun);
        
      //下一级审核人
        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
        mmap.put("approveid", configlis.get(0).getLevel1id());
        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/edit";
    }

    /**
     * 修改保存项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.updateSjProjectDesignFun(sjProjectDesignFun));
    }

    /**
     * 删除项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sjProjectDesignFunService.deleteSjProjectDesignFunByIds(ids));
    }
    
    @GetMapping("/p4fun/{id}")
    public String p4fun(ModelMap mmap,@PathVariable("id") Long id)
    {
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	//判断是成员，还是管理员
    	List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
    	//看个人
        int flag = 0;//成员
    	if(getSysUser().isShowRoleIds(roleIds)){
    		SjProjectPeople sjProjectPeople = new SjProjectPeople();
            sjProjectPeople.setDeleteFlag(1);
            sjProjectPeople.setGcProjectid(id);
            sjProjectPeople.setCode(getUserId().toString());
            List<SjProjectPeople> peoplelis = sjProjectPeopleService.selectSjProjectPeopleList(sjProjectPeople);
            if(peoplelis!=null && peoplelis.size()>0){
            	for(SjProjectPeople po1:peoplelis){
                	if(po1.getpId()==0l){
                		flag = 1;//领导
                		break;
                	}
                }
            }
        }else{
        	flag = 1;//领导
        }
        mmap.put("flag", flag);
        return "yy/project/projectDetailFun";
    }
    
    /**
     * 查询项目设计工作联系函列表
     */
    @PostMapping("/p4listfun")
    @ResponseBody
    public TableDataInfo p4listfun(YyProjectDesignFun sjProjectDesignFun)
    {
    	startPage();
    	sjProjectDesignFun.setDeleteFlag(1);
    	List<Map> list = sjProjectDesignFunService.selectFunAll(sjProjectDesignFun);
    	
//        startPage();
//        sjProjectDesignFun.setDeleteFlag(1);
//        List<YyProjectDesignFun> list = sjProjectDesignFunService.selectSjProjectDesignFunList(sjProjectDesignFun);
        
//        for(YyProjectDesignFun ms:list){
//        	YyProject po = gcProjectService.selectGcProjectById(ms.getGcProjectid());
//        	ms.setProjectName(po.getName());
//        }
        return getDataTable(list);
    }
    
    @GetMapping("/p4funfa/{id}")
    public String p4funfa(ModelMap mmap,@PathVariable("id") Long id)
    {
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	//判断是成员，还是管理员
    	List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
    	//看个人
        int flag = 0;//成员
    	if(getSysUser().isShowRoleIds(roleIds)){
    		SjProjectPeople sjProjectPeople = new SjProjectPeople();
            sjProjectPeople.setDeleteFlag(1);
            sjProjectPeople.setGcProjectid(id);
            sjProjectPeople.setCode(getUserId().toString());
            List<SjProjectPeople> peoplelis = sjProjectPeopleService.selectSjProjectPeopleList(sjProjectPeople);
            if(peoplelis!=null && peoplelis.size()>0){
            	for(SjProjectPeople po1:peoplelis){
                	if(po1.getpId()==0l){
                		flag = 1;//领导
                		break;
                	}
                }
            }
        }else{
        	flag = 1;//领导
        }
        mmap.put("flag", flag);
        return "yy/project/projectDetailFun4Fa";
    }
    
    @GetMapping("/p4funlai/{id}")
    public String p4funlai(ModelMap mmap,@PathVariable("id") Long id)
    {
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	//判断是成员，还是管理员
    	List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
    	//看个人
        int flag = 0;//成员
    	if(getSysUser().isShowRoleIds(roleIds)){
    		SjProjectPeople sjProjectPeople = new SjProjectPeople();
            sjProjectPeople.setDeleteFlag(1);
            sjProjectPeople.setGcProjectid(id);
            sjProjectPeople.setCode(getUserId().toString());
            List<SjProjectPeople> peoplelis = sjProjectPeopleService.selectSjProjectPeopleList(sjProjectPeople);
            if(peoplelis!=null && peoplelis.size()>0){
            	for(SjProjectPeople po1:peoplelis){
                	if(po1.getpId()==0l){
                		flag = 1;//领导
                		break;
                	}
                }
            }
        }else{
        	flag = 1;//领导
        }
        mmap.put("flag", flag);
        return "yy/project/projectDetailFun4lai";
    }

    @PostMapping("/p4list")
    @ResponseBody
    public TableDataInfo p4list(YyProjectDesignFun sjProjectDesignFun)
    {
    	startPage();
        sjProjectDesignFun.setDeleteFlag(1);
        sjProjectDesignFun.setType(1);//发函1 来函0
        List<YyProjectDesignFun> list = sjProjectDesignFunService.selectSjProjectDesignFunList(sjProjectDesignFun);
        
        for(YyProjectDesignFun ms:list){
        	YyProject po = gcProjectService.selectGcProjectById(ms.getGcProjectid());
        	ms.setProjectName(po.getName());
        }
        return getDataTable(list);
    }
    
    @PostMapping("/p4list4lai")
    @ResponseBody
    public TableDataInfo p4list4lai(YyProjectDesignFun sjProjectDesignFun)
    {
    	startPage();
        sjProjectDesignFun.setDeleteFlag(1);
        sjProjectDesignFun.setType(0);//发函1 来函0
        List<YyProjectDesignFun> list = sjProjectDesignFunService.selectSjProjectDesignFunList(sjProjectDesignFun);
        
        for(YyProjectDesignFun ms:list){
        	YyProject po = gcProjectService.selectGcProjectById(ms.getGcProjectid());
        	ms.setProjectName(po.getName());
        }
        return getDataTable(list);
    }
    
    @GetMapping("/funPrint/{id}")
    public String funPrint(@PathVariable("id") Long id, ModelMap mmap){
    	YyProjectDesignFun sjProjectDesignFun = sjProjectDesignFunService.selectSjProjectDesignFunById(id);
    	if(sjProjectDesignFun.getHfunfile()!=null && !sjProjectDesignFun.getHfunfile().equals("")){
        	String[] zlis = sjProjectDesignFun.getHfunfile().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zilwjvo", file);
        }else{
        	mmap.put("zilwjvo", "");
        }
        mmap.put("sjProjectDesignFun", sjProjectDesignFun);
        return prefix + "/funPrint";
    }
    
    //---------------------审批方法
    //申请人部门PID
    private List<SjProcessConfig> returnUser(Long deptId){
    	SysDept dept = deptService.selectDeptById(deptId);
    	SjProcessConfig sjProcessConfig = new SjProcessConfig();
        sjProcessConfig.setDeleteFlag(1);
        sjProcessConfig.setCode(processCode);
        sjProcessConfig.setDeptId(dept.getParentId());
        List<SjProcessConfig> configlis = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig);
		
        if(configlis==null || configlis.size()==0){
        	SjProcessConfig sjProcessConfig1 = new SjProcessConfig();
        	sjProcessConfig1.setDeleteFlag(1);
        	sjProcessConfig1.setCode("morenliucheng");
            List<SjProcessConfig> configlis1 = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig1);
            return configlis1;
        }
        return configlis;
    }
    
    /**
     * 修改保存项目立项
     */
    @Log(title = "商机立项", businessType = BusinessType.UPDATE)
    @PostMapping("/edit4check")
    @ResponseBody
    public AjaxResult edit4check(YyProjectDesignFun sjProjectDesignFun){
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.updateSjProjectDesignFun4check(sjProjectDesignFun));
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level1")
    public String level1(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectDesignFun obj = sjProjectDesignFunService.selectSjProjectDesignFunById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getHfunfile()!=null && !obj.getHfunfile().equals("")){
            	String[] zlis = obj.getHfunfile().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zilwjvo", file);
            }else{
            	mmap.put("zilwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            mmap.put("approveid", obj.getSprId());
            mmap.put("approvename", obj.getSpr());
        }
        
        return prefix + "/level1check";
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level2")
    public String level2(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectDesignFun obj = sjProjectDesignFunService.selectSjProjectDesignFunById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getHfunfile()!=null && !obj.getHfunfile().equals("")){
            	String[] zlis = obj.getHfunfile().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zilwjvo", file);
            }else{
            	mmap.put("zilwjvo", "");
            }
        	mmap.put("obj", obj);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            List<SjProcessConfig> configlis = returnUser(Long.valueOf(obj.getDeptId().toString()));
            mmap.put("approveid", configlis.get(0).getLevel3id());
            mmap.put("approvename", configlis.get(0).getLevel3name());
        }
        
        return prefix + "/level2check";
    }
    
    /**
     * 修改单据
     * @param taskid
     * @param mmap
     * @return
     */
    @GetMapping("/modify")
    public String modify(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	YyProjectDesignFun obj = sjProjectDesignFunService.selectSjProjectDesignFunById(Long.parseLong(p.getBusinessKey().toString()));
        	if(obj.getHfunfile()!=null && !obj.getHfunfile().equals("")){
            	String[] zlis = obj.getHfunfile().split(",");
            	String file = "";
            	for(int i=0;i<zlis.length;i++){
            		file += zlis[i]+",";
            	}
            	mmap.put("zilwjvo", file);
            }else{
            	mmap.put("zilwjvo", "");
            }
        	
        	mmap.put("obj", obj);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
        }
        
        return prefix + "/modifycheck";
    }
    
    
    //----回函
    /**
     * 新增项目设计工作联系函
     */
    @GetMapping("/add4lai/{id}")
    public String add4lai(@PathVariable("id") Long id, ModelMap mmap){
    	YyProject po = gcProjectService.selectGcProjectById(id);
    	mmap.put("gcProject", po);
    	
    	mmap.put("owner", getLoginName());
    	mmap.put("ownerId", getUserId());
    	mmap.put("deptName", getSysUser().getDept().getDeptName());
    	mmap.put("deptId", getSysUser().getDept().getDeptId());
    	
        return prefix + "/add4lai";
    }

    /**
     * 新增保存项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.INSERT)
    @PostMapping("/add4lai")
    @ResponseBody
    public AjaxResult add4laiSave(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setStatus(0);
    	sjProjectDesignFun.setDeleteFlag(1);
    	sjProjectDesignFun.setCreateUser(getLoginName());
    	sjProjectDesignFun.setCreateAt(new Date());
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.insertSjProjectDesignFun4check(sjProjectDesignFun));
    }

    /**
     * 修改项目设计工作联系函
     */
    @GetMapping("/edit4lai/{id}")
    public String edit4lai(@PathVariable("id") Long id, ModelMap mmap)
    {
        YyProjectDesignFun sjProjectDesignFun = sjProjectDesignFunService.selectSjProjectDesignFunById(id);
        
        if(sjProjectDesignFun.getHfunfile()!=null && !sjProjectDesignFun.getHfunfile().equals("")){
        	String[] zlis = sjProjectDesignFun.getHfunfile().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zilwjvo", file);
        }else{
        	mmap.put("zilwjvo", "");
        }
        mmap.put("sjProjectDesignFun", sjProjectDesignFun);
        
        return prefix + "/edit4lai";
    }

    /**
     * 修改保存项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.UPDATE)
    @PostMapping("/edit4lai")
    @ResponseBody
    public AjaxResult edit4hSave(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.updateSjProjectDesignFun4check(sjProjectDesignFun));
    }
    
    
    /**
     * 修改项目设计工作联系函
     */
    @GetMapping("/uploadFun/{id}")
    public String uploadFun(@PathVariable("id") Long id, ModelMap mmap)
    {
        YyProjectDesignFun sjProjectDesignFun = sjProjectDesignFunService.selectSjProjectDesignFunById(id);
        
        if(sjProjectDesignFun.getHfunfile()!=null && !sjProjectDesignFun.getHfunfile().equals("")){
        	String[] zlis = sjProjectDesignFun.getHfunfile().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += zlis[i]+",";
        	}
        	mmap.put("zilwjvo", file);
        }else{
        	mmap.put("zilwjvo", "");
        }
        mmap.put("sjProjectDesignFun", sjProjectDesignFun);
        
        return prefix + "/uploadFun";
    }
    
    /**
     * 修改保存项目设计工作联系函
     */
    @Log(title = "项目设计工作联系函", businessType = BusinessType.UPDATE)
    @PostMapping("/editFun")
    @ResponseBody
    public AjaxResult editFunSave(YyProjectDesignFun sjProjectDesignFun)
    {
    	sjProjectDesignFun.setStatus(8);
    	sjProjectDesignFun.setUpdateUser(getLoginName());
    	sjProjectDesignFun.setUpdateAt(new Date());
        return toAjax(sjProjectDesignFunService.updateSjProjectDesignFun4check(sjProjectDesignFun));
    }
}